package com.sz.pc.utils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.sz.pc.entity.model.constants.GlobalConstants;


/**
 * Servlet工具类
 *
 * @author liew
 */
public class ServletUtil {

    private static Logger logger = LoggerFactory.getLogger(ServletUtil.class);
    
    public  static final String  TOMCATE_PATH = getTomcatHomeByAbsolute();//tomcate的路径
   

    public static String getRequestUrl(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest)request;
        String queryString = req.getQueryString();
        queryString = StringUtils.isEmpty(queryString)?"": "?"+queryString;
        return req.getRequestURI()+queryString;
    }

    private static ThreadLocal<Map> servletContext = ThreadLocal.withInitial(() -> new HashMap());
    


    /**
     * Constant for the HTTP request ip address.
     */
    private static final String HTTP_REMOTE_ADDR = "org.framework.web.ServletConstants.RemoteAddr";

    
    private static ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<HttpServletResponse>();  

    public static HttpServletRequest getRequest() {
    	RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return request;  
    }

    
    public static HttpServletResponse getResponse() {
    	 return (HttpServletResponse) responseLocal.get();  
    }


    public static HttpSession getSession() {
        HttpServletRequest request = getRequest();
        HttpSession session = request != null ? request.getSession() : null;
        return session;
    }

    /**
     * 获得客户端端的session id
     */
    public static String getSessionId() {
        HttpSession httpSession = getSession();
        return (httpSession != null ? httpSession.getId() : "null");
    }

    /**
     * 获得客户端端的真实IP
     */
    public static String getRemoteAddr() {
        String ip = (String) servletContext.get().get(HTTP_REMOTE_ADDR);
        if (ip != null) {
            return ip;
        }
        return null;

    }

    public static void clearServletContext() {
        servletContext.get().clear();
    }


    /**
     * 获取IP地址
     */
    public static String getIpAddr() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return "127.0.0.1";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Cdn-Src-Ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取http端口
     */
    public static int getHttpPort(HttpServletRequest req) {
        try {
            return new URL(req.getRequestURL().toString()).getPort();
        } catch (MalformedURLException excp) {
            return 80;
        }
    }

    public static boolean isAjax(HttpServletRequest request){
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    //获取head传递的值
	public static String  getValueByHeadKey(String key){
		return ServletUtil.getRequest().getHeader(key);
	}
	public static String  getValueByReqKey(String key){
		return ServletUtil.getRequest().getParameter(key);
	}
	
	/**
	 * 获取访问的终端
	 * @return
	 */
	public static String getTerminal(){
		
		return ServletUtil.getRequest().getHeader(GlobalConstants.TERMINAL);
	}
	
	/**
	 * 获取访问的终端设备ID
	 * @return
	 */
	public static String getClientId(){
		
		return ServletUtil.getRequest().getHeader(GlobalConstants.CLIENTID);
	}
	
	/**
	 * 获取项目名
	 * @return
	 */
	public static String getProjectName(){
		String projectName = ServletUtil.getRequest().getContextPath();
		return projectName;
	}
	
	/**
	 * 通过request获取tomcat路径 注意一定要确保是一个request请求
	 * @return
	 */
	public static String getTomcatHome(){
		String path =ServletUtil.getRequest().getSession().getServletContext().getRealPath(""); 
		int index = path.indexOf("webapps");
		if(-1 == index){
			return path;
		}else{
			return path.substring(0, index+7);
		}
	}
	
	/**
	 * 通过ClassLoader获取tomcat路径 
	 * @return
	 */
	public static String getTomcatHomeByAbsolute(){
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		//String path = "/opt/tomcat/webapps/agent/WEB-INF/classes/";
		int index = path.indexOf("webapps");
		if(index != -1){
			path = path.substring(0,index)+"webapps";
		}
		logger.info("tomcat路径:"+path);
		return path;
	}

}
